package com.kingsoft.dc.khaos.innertype

import com.kingsoft.dc.khaos.metadata.KhaosStructField


/**
  * Created by chengguangqing on 2019/6/2.
  */
class Schema extends Serializable{

  private var _index: Map[String, Int] = _
  private var _schemas: Seq[KhaosStructField] = _

  def this(fields: Seq[KhaosStructField]){
    this()
    _schemas = fields
    _schemas.foldLeft(List.empty[KhaosStructField]){(result,cur) =>
      if(result.contains(cur)){
        throw new IllegalArgumentException(s"duplicate field '${cur.name}'")
      }
      else{
        result :+ cur
      }
    }
  }

  private def index():Unit={
    _index = _schemas.zipWithIndex.map{ case(field,index) =>
      (field.name,index)
    }.toMap
  }

  def fieldIndex(fieldName: String): Int = {
    _index.getOrElse(fieldName,
      throw new IllegalArgumentException(s"$fieldName does not exist"))
  }

  //def select(selector:Schema, tuple:List[_ <:])


  def toList():List[KhaosStructField] ={
    _schemas.toList
  }

  def size():Int ={
    _schemas.size
  }

  def get(index:Int):KhaosStructField ={
    _schemas(index)
  }

  def iterator(): Iterator[KhaosStructField] = {
    _schemas.iterator
  }

  def contains(field: String): Boolean = {
    _index.contains(field)
  }
  //
  override def toString: String = {
    _schemas.toString()
  }

  override def hashCode(): Int = _schemas.hashCode()
}
